﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Reflection;

namespace Elentok.Common.Helpers
{
  /// <summary>
  /// Contains Operating-System related helper methods
  /// </summary>
  public static class SystemHelper
  {
    #region Ctor
    static SystemHelper()
    {
      InitApplicationName();
    }
    #endregion

    // SYSTEM

    #region Application Name & ExecutablePath
    /// <summary>
    /// Gets the name of the application
    /// </summary>
    public static string ApplicationName { get; private set; }
    /// <summary>
    /// Gets the full path to this application's .exe
    /// </summary>
    public static string ExecutablePath { get; private set; }

    static void InitApplicationName()
    {
      Assembly assembly = Assembly.GetEntryAssembly();
      //if (assembly == null)
      //  throw new Exception("Can't find application name, no entry assembly");

      if (assembly != null)
      {
        ApplicationName = assembly.GetName().Name;
        ExecutablePath = assembly.Location;
      }
      else
        ApplicationName = "Unittests";
    }
    #endregion

    /// <summary>
    /// Returns the %ApplicationData%\{AssemblyName}
    /// </summary>
    /// <param name="createIfDoesNotExist">If true and the path doesn't exist, create it</param>
    /// <returns></returns>
    public static string GetUserSettingsPath(bool createIfDoesNotExist)
    {
      string root = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
      string path = Path.Combine(root, ApplicationName);

      DirectoryInfo dirInfo = new DirectoryInfo(path);
      if (!dirInfo.Exists && createIfDoesNotExist)
        dirInfo = Directory.CreateDirectory(path);

      if (dirInfo.Exists)
      {
        if ((dirInfo.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
        {
          dirInfo.Attributes |= FileAttributes.Hidden;
        }
      }

      return path;
    }

    /// <summary>
    /// Adds <paramref name="path"/> to the PATH environment variable
    /// (return true if added, or false if already in the path)
    /// </summary>
    /// <param name="target">Defines which scope to add the path to (system, user or process)</param>
    /// <param name="path"></param>
    /// <returns></returns>
    public static bool AddToPath(EnvironmentVariableTarget target, string path)
    {
      string currentPath = Environment.GetEnvironmentVariable("PATH", target);

      Regex re = new Regex("(^|;)" + Regex.Escape(path) + "(;|$)", RegexOptions.Compiled);

      Match match = re.Match(currentPath);
      if (match.Success)
        return false;
      
      currentPath += ";" + path;
      Environment.SetEnvironmentVariable("PATH", currentPath, target);
      return true;
    }


  }
}
